package com.company.huisuo.repository

import com.company.huisuo.network.api.CategoryApi
import com.company.huisuo.network.api.ProductApi
import com.company.huisuo.biz.bean.CategoryBean
import com.company.huisuo.biz.bean.ProductBean
import com.company.huisuo.biz.bean.ProductResponse
import com.company.huisuo.network.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 产品数据仓库
 */
class ProductRepository(private val productApi: ProductApi, private val categoryApi: CategoryApi) {
    
    /**
     * 获取产品分页列表
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @param categoryIds 分类ID列表（可选）
     */
    suspend fun getProductPage(
        pageNo: Int = 1,
        pageSize: Int = 20,
        categoryIds: String? = null
    ): Result<List<ProductBean>> = withContext(Dispatchers.IO) {
        try {
            val response = productApi.getProductPage(pageNo, pageSize, categoryIds)
            if (response.code == 0 && response.data?.list != null) {
                Result.success(response.data.list)
            } else {
                Result.failure(Exception(response.msg ?: "获取产品列表失败"))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }
    
    /**
     * 获取产品列表
     * @param pageNo 页码
     * @param pageSize 每页大小
     * @param categoryIds 分类ID列表（可选）
     */
    suspend fun getProductList(
        pageNo: Int = 1,
        pageSize: Int = 20,
        categoryIds: String? = null
    ): Result<List<ProductBean>> = withContext(Dispatchers.IO) {
        try {
            val response = productApi.getProductPage(pageNo, pageSize, categoryIds)
            if (response.code == 0 && response.data?.list != null) {
                Result.success(response.data.list)
            } else {
                Result.failure(Exception(response.msg ?: "获取产品列表失败"))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }
    
    /**
     * 获取分类列表
     */
    suspend fun getCategoryList(): Result<List<CategoryBean>> = withContext(Dispatchers.IO) {
        try {
            val response = categoryApi.getCategoryList()
            if (response.code == 0 && response.data != null) {
                Result.success(response.data)
            } else {
                Result.failure(Exception(response.msg ?: "获取分类列表失败"))
            }
        } catch (e: Exception) {
            Result.failure(Exception("网络请求失败: ${e.message}"))
        }
    }
}